﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.IO;
using System.Windows.Forms;

namespace LinuxManage
{
    public class Global
    {
        private static readonly XmlDocument SysConfig = new XmlDocument();
        private static readonly string SysConfigPath = System.Windows.Forms.Application.StartupPath + "\\SystemConfig.xml";
        public static bool Init()
        {
            try
            {
                SysConfig.Load(SysConfigPath);
                Config.host = GetValue("host");
                Config.user = GetValue("user");
                Config.passwd = GetValue("passwd");
            }
            catch (Exception)
            {
                MessageBox.Show("配置读取错误，请检查配置文件SystemConfig.xml");
                return false;
            }
            return true;

        }
        #region 读取设置配置文件
        public static String GetValue(String key)
        {
            String value = string.Empty;
            String path = @"//Root/appSettings/add[@key='" + key + "']";
            XmlNodeList xmlAdds = SysConfig.SelectNodes(path);

            if (xmlAdds.Count == 1)
            {
                XmlElement xmlAdd = (XmlElement)xmlAdds[0];

                value = xmlAdd.GetAttribute("value");
            }
            else
            {
                throw new Exception("读取" + key + "错误");
            }

            return value;
        }

        public static void SetValue(string strKey, string strValue)
        {
            XmlNodeList list = SysConfig.GetElementsByTagName("add");
            for (int i = 0; i < list.Count; i++)
            {
                if (list[i].Attributes[0].Value == strKey)
                {
                    list[i].Attributes[1].Value = strValue;
                }
            }
            StreamWriter swriter = new StreamWriter(SysConfigPath);
            XmlTextWriter xw = new XmlTextWriter(swriter);
            xw.Formatting = Formatting.Indented;
            SysConfig.WriteTo(xw);
            xw.Close();
            swriter.Close();
        }
        #endregion
    }
}
